基本介绍
Objective-C的异常比较像Java的异常处理,也有@finally的处理,不管异常是否捕获都都要执行。
异常处理捕获的语法:
@try {
<#statements#>
}
@catch (NSException *exception) {
<#handler#>
}
@finally {
<#statements#>
}
@catch{} 块 对异常的捕获应该先细后粗,即是说先捕获特定的异常,再使用一些泛些的异常类型。
自定义异常
新建SomethingException,SomeOverException这两个类,都继承自NSException类。
SomeException.h
#import <Foundation/Foundation.h>
@interface SomeException : NSException
@end
SomeException.m
#import "SomeException.h"
@implementation SomeException
@end
SomeOverException.h
#import <Foundation/Foundation.h>
@interface SomeOverException : NSException
@end
SomeOverException.m
#import "SomeOverException.h"
@implementation SomeOverException
@end
使用异常
创建Box,在某些条件下产生异常
Box.h
#import <Foundation/Foundation.h>
@interface Box : NSObject {
NSInteger number;
}
-(void) setNum : (NSInteger) num;
-(void) pushIn;
-(void) pushOut;
-(void) print;
@end
Box.m
#import "Box.h"
#import "SomeException.h"
#import "SomeOverException.h"
@implementation Box
-(id) init {
self = [super init];
if (self) {
[self setNum:0];
}
return self;
}
-(void) setNum : (NSInteger) num {
number = num;
if (number > 10) {
//抛出异常
NSException *exception = [SomeOverException
exceptionWithName:@"BoxWarningException"
reason:@"大于10"
userInfo:nil];
@throw exception;
} else if (number >= 6) {
NSException *exception = [SomeException
exceptionWithName:@"BoxWarningException"
reason:@"大于6小于10"
userInfo:nil];
@throw exception;
} else if (number < 0) {
NSException *exception = [SomeOverException
exceptionWithName:@"BoxUnderflowException"
reason:@"小于0"
userInfo:nil];
@throw exception;
}
}
-(void) pushIn {
[self setNum:number + 1];
}
-(void) pushOut {
[self setNum:number -1];
}
-(void) print {
NSLog(@"Box number is %ld.",number);
}
@end
捕获异常
#import <Foundation/Foundation.h>
#import "Box.h"
#import "SomeException.h"
#import "SomeOverException.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
// insert code here...
Box *box = [[Box alloc] init];
for (int i = 0; i < 6; i++) {
//捕获异常
@try {
[box pushIn];
} @catch (SomeException *exception){
NSLog(@"%@,%@",[exception name],[exception reason]);
} @catch (SomeOverException *exception){
NSLog(@"%@",[exception name]);
}@catch (NSException *exception) {
} @finally {
[box print];
}
}
}
return 0;
}
结果打印:
2016-10-10 10:03:05.955611 ExceptionDemo[16423:1308991] Box number is 1.
2016-10-10 10:03:05.955772 ExceptionDemo[16423:1308991] Box number is 2.
2016-10-10 10:03:05.955783 ExceptionDemo[16423:1308991] Box number is 3.
2016-10-10 10:03:05.955791 ExceptionDemo[16423:1308991] Box number is 4.
2016-10-10 10:03:05.955800 ExceptionDemo[16423:1308991] Box number is 5.
2016-10-10 10:03:05.956487 ExceptionDemo[16423:1308991] BoxWarningException,大于6小于10
2016-10-10 10:03:05.956509 ExceptionDemo[16423:1308991] Box number is 6.
Program ended with exit code: 0
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。